
import urllib.request
import os
from mz_decode import jandan_load_img


config={
    "folder":"./mm",
    "pages":5,
    "url":"http://jandan.net/ooxx/"
}


# 获取url 响应的内容
def getUrlContent(url,isDecode=False):
    
    req= urllib.request.Request(url);
    req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
    res= urllib.request.urlopen(url);

    return res.read().decode("utf-8") if(isDecode) else res.read() 


# 获取最新的页码URl
def getPageUrl(page):
    
    html = getUrlContent(config["url"],True)

    # 加23 刚好找到 [ 位置
    pageNum_before = html.find("current-comment-page")+23
    pageNum_after = html.find("]",pageNum_before)
    
    return config["url"]+"page-"+str(int(html[pageNum_before:pageNum_after])-page)+"#comments"


# 获取页面的照片
def getPagePicture(page):
    
    imgArr = []

    html = getUrlContent(getPageUrl(page),True)
    before = html.find('ol class="commentlist"')
    after = html.find('</ol',before);

    comments = html[before:after];
    img_start = comments.find('class="img-hash">')

    # print(comments)


    while img_start!=-1:
        
        img_start+=17
        
        img_end= comments.find('</span>',img_start);
        img_url = "http:"+jandan_load_img(comments[img_start:img_end])

        imgArr.append(img_url);

        # print(img_url)
        img_start = comments.find('class="img-hash">',img_end)

    # print(imgArr)

    return imgArr


# 保存图片
def saveImg(img_arr):
    
    print("一共"+str(len(img_arr))+"张图片\n")

    for i in img_arr:
        filename = i.split("/")[-1]

        with open(filename,"wb") as f:
            img = getUrlContent(i)
            f.write(img) 

    print("下载完成!!!!!!!\n\n")


# 下载主函数
def download_mm():

    os.chdir(config["folder"])

    arr = range(config["pages"])
    
    for i in arr:
        
        print("开始下载第"+str(i+1)+"页的妹子\n")
        saveImg(getPagePicture(i+5))
    
    
    print("一共"+str(len(arr))+"页妹子被你下完了\n")

download_mm()


    
    
    
